package com.vhans.extend.quartz;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.vhans.core.domain.*;
import com.vhans.core.redis.RedisService;
import com.vhans.db.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Set;

import static com.vhans.core.constant.RedisConstant.*;

/**
 * 执行定时任务
 *
 * @author vhans
 */
@SuppressWarnings(value = "all")
@Component("timedTask")
public class TimedTask {

    @Autowired
    private AVisitLogMapper visitLogMapper;

    @Autowired
    private BAppointmentMapper appointmentMapper;

    @Autowired
    private BActivityMapper activityMapper;

    @Autowired
    private BCompetitionMapper competitionMapper;

    @Autowired
    private BHelpMapper helpMapper;

    @Autowired
    private BRecordMapper recordMapper;

    @Autowired
    private BQuizMapper quizMapper;

    @Autowired
    private BCommentMapper commentMapper;

    @Autowired
    private BUserLikeMapper userLikeMapper;

    @Autowired
    private RedisService redisService;

    /**
     * 清除平台访问记录
     */
    public void clear() {
        redisService.deleteObject(UNIQUE_VISITOR);
    }

    /**
     * 清除一周前的访问日志
     */
    public void clearVistiLog() {
        DateTime endTime = DateUtil.beginOfDay(DateUtil.offsetDay(new Date(), -7));
        visitLogMapper.deleteVisitLog(endTime);
    }

    /**
     * 设置点赞记录
     */
    public void setLike() {
        // 用户id
        int userId = StpUtil.getLoginIdAsInt();
        // 获取用户点赞的记录ids及清除缓存
        String userLikeRecordKey = USER_RECORD_LIKE + userId;
        List<Integer> recordIds = redisService.getSet(userLikeRecordKey)
                .stream().map(item -> Integer.valueOf(item.toString())).toList();
        redisService.deleteSet(userLikeRecordKey);
        // 获取用户点赞的题目ids及清除缓存
        String userLikeQuizKey = USER_RECORD_LIKE + userId;
        List<Integer> quizIds = redisService.getSet(userLikeQuizKey)
                .stream().map(item -> Integer.valueOf(item.toString())).toList();
        redisService.deleteSet(userLikeQuizKey);
        // 获取用户点赞的评论ids及清除缓存
        String userLikeCommentKey = USER_RECORD_LIKE + userId;
        List<Integer> commentIds = redisService.getSet(userLikeCommentKey)
                .stream().map(item -> Integer.valueOf(item.toString())).toList();
        redisService.deleteSet(userLikeCommentKey);
        // 将记录、题目、评论的点赞信息添加入用户点赞数据库
        userLikeMapper.saveBatchUserLikeRecord(userId, recordIds);
        userLikeMapper.saveBatchUserLikeQuiz(userId, quizIds);
        userLikeMapper.saveBatchUserLikeComment(userId, commentIds);
        // 设置记录、题目、评论的点赞量
        recordIds.forEach(item -> {
            Integer likeNumber = redisService.getHash(RECORD_LIKE_COUNT, item.toString());
            recordMapper.updateById(BRecord.builder().id(item).likeNumber(likeNumber).build());
        });
        quizIds.forEach(item -> {
            Integer likeNumber = redisService.getHash(QUIZ_LIKE_COUNT, item.toString());
            quizMapper.updateById(BQuiz.builder().id(item).likeNumber(likeNumber).build());
        });
        commentIds.forEach(item -> {
            Integer likeNumber = redisService.getHash(COMMENT_LIKE_COUNT, item.toString());
            commentMapper.updateById(BComment.builder().id(item).likeNumber(likeNumber).build());
        });
    }

    /**
     * 设置约起过期
     */
    public void setExpire() {
        List<Integer> appointmentIds = appointmentMapper.selectAppointmentExpire();
        List<Integer> activityIds = activityMapper.selectActivityExpire();
        List<Integer> competitionIds = competitionMapper.selectCompetitionExpire();
        List<Integer> helpIds = helpMapper.selectHelpExpire();
        appointmentIds.forEach(item -> {
            appointmentMapper.updateById(BAppointment.builder().id(item).status(5).build());
        });
        activityIds.forEach(item -> {
            activityMapper.updateById(BActivity.builder().id(item).status(5).build());
        });
        competitionIds.forEach(item -> {
            competitionMapper.updateById(BCompetition.builder().id(item).status(5).build());
        });
        helpIds.forEach(item -> {
            helpMapper.updateById(BHelp.builder().id(item).status(5).build());
        });
    }
}